package gti310.tp3.parser;

import gti310.tp3.GraphHolder;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

public class ConcreteParser implements Parser<Object> {

	private static final String SEPARATOR = "\t";
	private static final String END_FILE_SYMBOL = "$";

	@Override
	public GraphHolder parse(String filename) {
		return createDataStructure(filename);
	}

	private GraphHolder createDataStructure(String filename) {
		// Reading
		BufferedReader graphIn;
		String strLine;
		List<String> strlist = new ArrayList<String>();

		try {

			graphIn = new BufferedReader(new FileReader(filename));

			while ((strLine = graphIn.readLine()) != null) {
				strlist.add(strLine);
			}

		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
			return null;
		}

		// Parsing
		ListIterator<String> iterator = strlist.listIterator();
		List<String> paramList = new ArrayList<String>();
		List<String[]> verticleList = new ArrayList<String[]>();
		String currentValue;
		String[] lineArray;

		while (iterator.hasNext()) {
			currentValue = iterator.next();
			lineArray = currentValue.split(SEPARATOR);
			if (currentValue.equalsIgnoreCase(END_FILE_SYMBOL)) {
				if (iterator.hasNext())
					return null; // bad file
			} else if (lineArray.length > 1) {
				verticleList.add(lineArray);
			} else {
				paramList.add(currentValue);
			}
		}
		return new GraphHolder(paramList, verticleList);

	}

}
